﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using PSE.LogPackager;
using PSE.Framework.UI.Resources;
using System.Diagnostics;
using Sinacor.Infra.UI.ErrorLoggingEnvironment;

namespace Sinacor.Infra.UI.Controls.SmartClient
{
    public class SinacorErrorWindow : System.Windows.Window
    {
        public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(SinacorErrorWindow), new FrameworkPropertyMetadata(null));

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty ErrorDetailProperty = DependencyProperty.Register("ErrorDetail", typeof(string), typeof(SinacorErrorWindow), new FrameworkPropertyMetadata(null));

        public string ErrorDetail
        {
            get { return (string)GetValue(ErrorDetailProperty); }
            set { SetValue(ErrorDetailProperty, value); }
        }

        public static readonly DependencyProperty ShowCollectErrorProperty = DependencyProperty.Register("ShowCollectError", typeof(bool), typeof(SinacorErrorWindow), new FrameworkPropertyMetadata(true));

        public bool ShowCollectError
        {
            get { return (bool)GetValue(ShowCollectErrorProperty); }
            set { SetValue(ShowCollectErrorProperty, value); }
        }

        private Uri _sourceAddress;
        private PSE.Framework.ErrorLogging.LogData _logData;
        
        public SinacorErrorWindow(string message, string title, Uri sourceAddress, PSE.Framework.ErrorLogging.LogData logData)
        {
            this.Title = title;
            this.Message = message;
            this.ErrorDetail = logData.ToString();

            _sourceAddress = sourceAddress;
            _logData = logData;

            this.ShowCollectError = _logData != null;

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.SetResourceReference(StyleProperty, "ControlErrorWindow");

            CommandBindings.Add(new CommandBinding(SinacorWindowCommands.Close, btnClose_Click));

            CommandBindings.Add(new CommandBinding(SinacorErrorWindowCommands.Continue, btnContinue_Click));
            CommandBindings.Add(new CommandBinding(SinacorErrorWindowCommands.CollectError, btnCollectError_Click));

            this.TryUpdateLayout();
        }

        void TryUpdateLayout()
        {
            try { this.UpdateLayout(); }
            catch { }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            Grid header = this.GetTemplateChild("GridDragMove") as Grid;
            header.MouseLeftButtonDown += new MouseButtonEventHandler(header_MouseLeftButtonDown);
        }

        private void header_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnContinue_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnCollectError_Click(object sender, RoutedEventArgs e)
        {
            
            try
            {
                LogPackager logPackager = new LogPackager();
                string supportEmail = logPackager.SupportEmail;
                string packageFile = null;

                // Coleta e empacota os arquivos
                if (this.Owner != null && this.Owner.IsLoaded)
                {
                    packageFile = logPackager.Pack(_sourceAddress, _logData, this.Owner);
                }
                else
                {
                    packageFile = logPackager.Pack(_sourceAddress, _logData);
                }

                string message = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.RelatorioErrosGeradoSucesso", packageFile, supportEmail);

                if (SinacorMessageBox.Show(message, SinacorMessageBoxButton.OkCancel, SinacorMessageBoxImage.Information) == SinacorMessageBoxResult.Ok)
                {
                    string subject = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Label.ColetarErros");

                    string errorMessage = (_logData.Message as Exception).Message;
                    string menuPath = "";
                    string moduleName = "";
                    string title = "";

                    if (_logData.Enviroment != null && _logData.Enviroment is UserInterfaceEnvironmentData)
                    {
                        UserInterfaceEnvironmentData uiEnvironmentData = (UserInterfaceEnvironmentData)_logData.Enviroment;
                        menuPath = uiEnvironmentData.SinacorMenuPath;
                        title = uiEnvironmentData.SinacorWindowTitle;
                        
                        string moduleId = uiEnvironmentData.SinacorModule;

                        if(!String.IsNullOrEmpty(moduleId))
                            moduleName = (string)ResourceProviderManager.GetResourceProvider().TryGetResource(string.Format("Common.Menu.Label.{0}", moduleId));
                    }

                    string body = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.AnexarRelatorioErros", moduleName, title, menuPath, errorMessage, packageFile);
                    
                    // Codifica o assunto e o corpo do e-mail e troca o "+" (espaço) pelo código hexa
                    subject = System.Web.HttpUtility.UrlEncode(subject, Encoding.Default).Replace("+", Uri.HexEscape(' '));

                    // Abrir e-mail
                    Process.Start(string.Format(@"mailto:{0}?subject={1}&body={2}", supportEmail, subject, body));
                }
            }
            catch (Exception ex)
            {
                Sinacor.Infra.UI.ErrorLogging.ErrorLogger.WriteLog(PSE.Framework.ErrorLogging.LogType.Error, ex);

                SinacorMessageBox.Show((string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.NaoFoiPossivelGerarRelatorioErros"), SinacorMessageBoxImage.Error);
            }

            this.Close();
        }
    }
}
